package com.baijiaoxi.common.utils.jdk;

import com.baijiaoxi.common.model.base.CommonError;
import com.baijiaoxi.common.model.base.CoreException;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

@Slf4j
public class PackageScanner {
    public interface ClassFilter {
        boolean isMatched(Class clazz);
    }


    public static List<Class<?>> scanPackage(String packageName, ClassFilter classFilter) {
        List<Class<?>> classes = new ArrayList<>();
        String packagePath = packageName.replace('.', '/');
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        try {
            Enumeration<URL> resources = classLoader.getResources(packagePath);
            while (resources.hasMoreElements()) {
                URL resource = resources.nextElement();
                if ("jar".equalsIgnoreCase(resource.getProtocol())) {
                    //转换为JarURLConnection
                    JarURLConnection connection = (JarURLConnection) resource.openConnection();
                    if (connection != null) {
                        JarFile jarFile = connection.getJarFile();
                        if (jarFile != null) {
                            //得到该jar文件下面的类实体
                            Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries();
                            while (jarEntryEnumeration.hasMoreElements()) {
                                JarEntry entry = jarEntryEnumeration.nextElement();
                                String jarEntryName = entry.getName();
                                //这里我们需要过滤不是class文件和不在basePack包名下的类
                                if (jarEntryName.contains(".class") && jarEntryName.replaceAll("/", ".").startsWith(packageName)) {
                                    String className = jarEntryName.substring(0, jarEntryName.lastIndexOf(".")).replace("/", ".");
                                    if (!className.contains("$")) {
                                        Class cls = Class.forName(className);
                                        if (classFilter.isMatched(cls))
                                            classes.add(cls);
                                    }
                                }
                            }
                        }
                    }
                } else {
                    File file = new File(resource.getFile());
                    scanClasses(file, packageName, classes, classFilter);
                }
            }
        } catch (Exception e) {
            throw CoreException.create(CommonError.scanPackageError, e, packagePath);
        }
        return classes;
    }

    private static void scanClasses(File directory, String packageName, List<Class<?>> classes, ClassFilter classFilter) {
        if (directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        String subPackageName = packageName + "." + file.getName();
                        scanClasses(file, subPackageName, classes, classFilter);
                    } else if (file.getName().endsWith(".class")) {
                        String className = packageName + '.' + file.getName().substring(0, file.getName().length() - 6);
                        try {
                            Class<?> clazz = Class.forName(className);
                            if (classFilter.isMatched(clazz))
                            classes.add(clazz);
                        } catch (ClassNotFoundException e) {
                            throw CoreException.create(CommonError.scanPackageError, e, className);
                        }
                    }
                }
            }
        }
    }

}
